package com.qfedu.buy.gateway.filter;

import com.qfedu.buy.common.config.RedisKeyConfig;
import com.qfedu.buy.common.config.SystemConfig;
import com.qfedu.buy.common.dto.UserTokenDto;
import com.qfedu.buy.common.util.RedissonUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: NeighborBuy
 * @description:
 * @author: Feri(邢朋辉)
 * @create: 2021-01-28 11:53
 */
@Component
public class TokenTimeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request=exchange.getRequest();
        //校验请求消息头 是否包含令牌
        if(request.getHeaders().containsKey(SystemConfig.TOKEN_HEADER)){
            //校验令牌是否有效
            String token=request.getHeaders().getFirst(SystemConfig.TOKEN_HEADER);
            if(RedissonUtil.isHave(RedisKeyConfig.USER_TOKEN+token)){
                //令牌有效  更新令牌的有效期
                UserTokenDto dto=(UserTokenDto)RedissonUtil.getObj(RedisKeyConfig.USER_TOKEN+token);
                RedissonUtil.expire(RedisKeyConfig.USER_TOKEN+token,RedisKeyConfig.USER_TOKEN_TIME);
                RedissonUtil.expire(RedisKeyConfig.USER_PHONE+dto.getPhone()+":"+dto.getType(),RedisKeyConfig.USER_TOKEN_TIME);
                //传递自定义消息头传递 令牌对应的用户id
                request.mutate().header(SystemConfig.USER_ID,dto.getId()+"");
            }
        }
        return chain.filter(exchange);
    }
}